package com.imoblife.brainwavestus.oldMedia;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.security.SecureRandom;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;

import com.imoblife.brainwavestus.oldDownloadFrame.Commmand;
import com.imoblife.brainwavestus.util.DebugUtil;

import android.content.Context;
import android.content.res.AssetFileDescriptor;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnErrorListener;

public class MusicMediaPlayer {

	static final String TAG = "MusicMediaPlayer";

	static String rootPath;

	private static int offset = 100;

	static MediaPlayer mediaPlayer;

	static {
		rootPath = "/sdcard/.brainwaves-tus/";
		mediaPlayer = new MediaPlayer();
	}

	public MediaPlayer getMediaPlayer() {

		return mediaPlayer;

	}

	private String fileName;

	boolean istop = true;

	public boolean isStop() {
		return istop;
	}

	public void stop() {
		istop = true;
	}

	public MusicMediaPlayer(String fileName) {
		this.fileName = fileName.replace(" ", "+");
		DebugUtil.debug(TAG, "����������" + fileName);
		musicMediaPlayer = this;
	}

	static MusicMediaPlayer musicMediaPlayer;

	public static MusicMediaPlayer getMusicMediaPlayerInstence() {

		return musicMediaPlayer;
	}

	public void releasePlayer() {
		if (mediaPlayer != null) {
			mediaPlayer.release();
			mediaPlayer = null;
		}
	}

	public boolean decryptPlay(final Context in) {
		DebugUtil.debug(TAG, "�����ļ�������" + fileName);
		mediaPlayer.reset();
		mediaPlayer.release();
		mediaPlayer = new MediaPlayer();
		istop = true;
		String subPath = fileName.substring(fileName.indexOf(".") + 1) + "/";
		try {

			// copyData(subPath + fileName);

			if (!decryptAudioFile(subPath + fileName, in)) {

				DebugUtil.debug(TAG, "�����ļ�����ʧ��" + fileName);

				// Commmand.makeMusicReDownLoadCommand(
				// fileName.replace("+", " "), in);
				// mediaPlayer.reset();
				// return false;
			}

			RandomAccessFile accessFile = new RandomAccessFile(rootPath
					+ subPath + fileName, "rwd");

			mediaPlayer.setDataSource(accessFile.getFD(), 100,
					accessFile.length() - 108);
			mediaPlayer.prepare();
			mediaPlayer.start();
			accessFile.close();
			DebugUtil.debug(TAG, "�����ļ����ųɹ�" + fileName);
			istop = false;
			return true;
		} catch (Exception e) {
			DebugUtil.debug(TAG, "�����ļ�����ʧ��" + fileName);
			Commmand.makeMusicReDownLoadCommand(fileName.replace("+", " "), in);
			mediaPlayer.reset();
			return false;
		}

	}

	public void encryptStop(Context in) {

		if (istop) {
			DebugUtil.debug(TAG, fileName + ">>�ϴν��ܲ���ʧ�� �˴β�����");
			return;
		}

		String subPath = fileName.substring(fileName.indexOf(".") + 1) + "/";

		if (mediaPlayer.isPlaying()) {

			mediaPlayer.stop();
		}
		mediaPlayer.reset();
		encryptAudioFile(subPath + fileName, in);

		istop = true;
	}

	/**
	 * ��ȡ��Կ
	 * 
	 * @param mode
	 *            ���ܻ����
	 * @param context
	 * @return
	 */
	private Cipher getCipher(int mode, Context context) {

		SecureRandom sr = new SecureRandom();
		// ����Կ�ļ��л�ȡԭʼ��Կ���
		byte[] rawKeyData = null;

		InputStream fileInputStream;
		try {
			fileInputStream = context.getAssets().open("icon.apk");
			rawKeyData = new byte[fileInputStream.available()];
			System.out.println(rawKeyData.length);
			fileInputStream.read(rawKeyData);
			fileInputStream.close();

			for (int i = 0; i < rawKeyData.length - 1; i += 2) {
				byte tmp = rawKeyData[i + 1];
				rawKeyData[i + 1] = rawKeyData[i];
				rawKeyData[i] = tmp;
			}

			// ����һ��DESKeySpec����
			DESKeySpec dks = new DESKeySpec(rawKeyData);
			// ����һ����Կ������Ȼ�������DESKeySpec����ת����Secret Key����
			SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
			SecretKey key = keyFactory.generateSecret(dks);
			// Cipher����ʵ����ɽ��ܲ���
			Cipher cipher = Cipher.getInstance("DES");
			cipher.init(mode, key, sr);
			return cipher;
		} catch (Exception e) {
			
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * ������Ƶ�ļ����
	 * 
	 * @param audioFileName
	 * @return ���ܳɹ�����true ��֮ false
	 */

	public boolean encryptAudioFile(String audioFileName, Context context) {

		try {
			// 1 ���������ļ�
			RandomAccessFile randomAccessFile = new RandomAccessFile(rootPath
					+ audioFileName, "rwd");

			// 2 �����Կ
			Cipher c1 = getCipher(Cipher.ENCRYPT_MODE, context);

			// 3 ��ȡ�������
			byte[] bs = new byte[104];
			randomAccessFile.seek(offset);
			randomAccessFile.read(bs);

			// 4 ִ�м���
			byte[] cipherByte = c1.doFinal(bs);

			// 5����������
			randomAccessFile.seek(offset);
			randomAccessFile.write(cipherByte, 0, 104);
			randomAccessFile.seek(randomAccessFile.length() - 8);
			randomAccessFile.write(cipherByte, 104, 8);

			// 6���ܳɹ�
			randomAccessFile.close();
			DebugUtil.debug(TAG, "���ܳɹ�");
			return true;

		} catch (FileNotFoundException e) {
			
			e.printStackTrace();
		} catch (IOException e) {
			
			e.printStackTrace();
		} catch (IllegalBlockSizeException e) {
			
			e.printStackTrace();
		} catch (BadPaddingException e) {
			
			e.printStackTrace();
		}
		DebugUtil.debug(TAG, "����ʧ��");
		return false;
	}

	/**
	 * ������Ƶ�ļ����
	 * 
	 * @param audioFileName
	 * @return ���ܳɹ�����true ��֮ false
	 */
	public boolean decryptAudioFile(String audioFileName, Context context) {

		try {
			// 1 ������Ҫ���ܵ��ļ�
			RandomAccessFile randomAccessFile = new RandomAccessFile(rootPath
					+ audioFileName, "rwd");

			// 2 ��ȡ�����ֶ�
			byte[] bs = new byte[112];
			randomAccessFile.seek(offset);
			randomAccessFile.read(bs, 0, 104);
			randomAccessFile.seek(randomAccessFile.length() - 8);
			randomAccessFile.read(bs, 104, 8);

			boolean isDecrypted = true;

			for (int i = 1; i < 9; i++) {
				System.out.println(bs[bs.length - i]);
				if (bs[bs.length - i] != -1) {
					isDecrypted = false;
				}

			}

			if (isDecrypted) {
				System.out.println("�ϴ��Ѿ�����");
				randomAccessFile.close();
				return true;
			}

			// 3 ��ȡ��Կ
			Cipher c1 = getCipher(Cipher.DECRYPT_MODE, context);

			// 4 ִ�н���
			byte[] cipherByte = c1.doFinal(bs);

			// 5�ظ��ļ�
			// randomAccessFile.setLength(randomAccessFile.length() - 8);
			randomAccessFile.seek(offset);
			randomAccessFile.write(cipherByte);
			randomAccessFile.seek(randomAccessFile.length() - 8);
			randomAccessFile
					.write(new byte[] { -1, -1, -1, -1, -1, -1, -1, -1 });
			// 6���ܳɹ�
			randomAccessFile.close();
			System.out.println("// 6���ܳɹ�");
			return true;

		} catch (FileNotFoundException e) {
			
			e.printStackTrace();
		} catch (IOException e) {
			
			e.printStackTrace();
		} catch (IllegalBlockSizeException e) {
			
			e.printStackTrace();
		} catch (BadPaddingException e) {
			
			e.printStackTrace();
		}
		System.out.println("// 6����ʧ��");
		return false;
	}

	public void copyData(String audioFileName) throws IOException {

		File out = new File(rootPath + audioFileName + ".copy");

		if (out.exists()) {
			return;
		}

		File in = new File(rootPath + audioFileName);

		FileOutputStream fileOutputStream = new FileOutputStream(out);

		FileInputStream fileInputStream = new FileInputStream(in);

		byte[] bt = new byte[1028];
		int len = fileInputStream.read(bt);
		while (len != -1) {
			fileOutputStream.write(bt, 0, len);
			len = fileInputStream.read(bt);
		}
		fileOutputStream.close();
		fileInputStream.close();
	}

}
